<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
class Engagement {
	public function engagement_for($bricabox)
	{
		$type = $bricabox->engagement_type;
		if (!$type)
			$type = 'button';
			
		$klass = $this->_load_klass($type);
		return $klass;
	}
	
	public function record_engagement($bricabox, $content, $user, $type, $instance, $value)
	{
		log_message('debug', 'record_engagement '.$type);
		
		$CI =& get_instance();
		$CI->load->database();
		
		$CI->db->query('insert into engagements (created_at,updated_at,user_id,content_id,engagement_type,engaged_via,value)
		values(NOW(),NOW(),?,?,?,?,?)',
		array(
			$user->id,
			$content->id,
			$type,
			get_class($instance),
			$value
		));
		
		// record the activity
		$CI->load->model('Activity_model');
		$CI->Activity_model->log_activity(array(
			'action' 		=> strpos(strtolower(get_class($instance)), 'fivestar') !== false
								? 'rated'
								: $bricabox->engage_term_past_tense,
			'extra_data' 	=> serialize(array('v' => $value)),
			'activity_type' => 'engagement',
			'content_id'	=> $content->id,
			'object'		=> $content->field1_value,
			'bricabox_id'	=> $bricabox->id,
			'subject'		=> username($user)
		));
		
		// update the cached count, too
		$CI->db->query('update contents
			set cached_eng_count=cached_eng_count+1
			where id = ?', array($content->id));
		
		return true;
	}
	
	private function _load_klass($type)
	{
		$klass_name = ucfirst($type).'Engagement';
		return new $klass_name;
	}
}

class EngagementType {
	public $CI;
	
	function __construct()
	{
		$this->CI =& get_instance();
	}
	
	function form_for_entry($bricabox, $content, $user)
	{
	}
	
	function count_for_entry($bricabox, $content)
	{
	}
	
	function small_form_for_entry($bricabox, $content, $user)
	{
	}
	
	function small_count_for_entry($bricabox, $content)
	{
	}
	
	function get_count_for($bricabox, $content)
	{
	}
	
	function user_engaged($bricabox, $content, $user)
	{
	}
	
	/**
	* callbacks
	*/
	function on_click($bricabox, $content, $user, $type, $value)
	{	
	}
	
	function on_create_entry($bricabox, $content, $user, $type, $value)
	{
	}
}

/**
* Button
*/
class ButtonEngagement extends EngagementType {
	function form_for_entry($bricabox, $content, $user)
	{
		if (!$this->CI->userland->logged_in())
			return '<a href="/sign_up_or_log_in">sign up or log in to interact</a>';
			
		if ($this->user_engaged($bricabox, $content, $user))
			return "You already {$bricabox->engage_term_past_tense}";
		else
			return <<<HTML
<form action="/bricabox/{$bricabox->id}/handle_engagement" method="post">
	<input type="hidden" name="eng[type]" value="click" />
	<input type="hidden" name="eng[eng_type]" value="button" />
	<input type="hidden" name="eng[content_id]" value="{$content->id}" />
	<input type="hidden" name="eng[user_id]" value="{$user->id}" />
	<input type="hidden" name="eng[redirect]" value="/{$_SERVER['QUERY_STRING']}" />
	<input type="submit" value="{$bricabox->engage_button_label}" />
</form>
HTML;
	}
	
	function count_for_entry($bricabox, $content)
	{
		$cnt = $this->get_count_for($bricabox, $content);
		return "{$cnt} {$bricabox->engage_term_past_tense}";
	}
	
	function small_form_for_entry($bricabox, $content, $user)
	{
		 if (!$this->CI->userland->logged_in())
			return '<a href="/sign_up_or_log_in">sign up or log in to interact</a>';

		if ($this->user_engaged($bricabox, $content, $user))
		{
			$and = $this->get_count_for($bricabox, $content) - 1;
			if ($and)
			{
				$and .= ' ' . ($and == 1 ? 'other' : 'others');
				return "You and {$and} {$bricabox->engage_term_past_tense}";
			}
			else
			{
				return "You {$bricabox->engage_term_past_tense}";
			}
		}
		else
			return <<<HTML
<form action="/bricabox/{$bricabox->id}/handle_engagement" method="post" style="display: inline;">
	<input type="hidden" name="eng[type]" value="click" />
	<input type="hidden" name="eng[eng_type]" value="button" />
	<input type="hidden" name="eng[content_id]" value="{$content->id}" />
	<input type="hidden" name="eng[user_id]" value="{$user->id}" />
	<input type="hidden" name="eng[redirect]" value="/{$_SERVER['QUERY_STRING']}" />
	<input type="submit" value="{$bricabox->engage_button_label}" style="vertical-align: middle;" />
</form>
HTML;
	}
	
	function small_count_for_entry($bricabox, $content)
	{
		return '';
	}
	
	function get_count_for($bricabox, $content)
	{
		$query = $this->CI->db->query('select cached_eng_count from contents
			where id = ?', array($content->id));
		return $query->first_row()->cached_eng_count;
	}
	
	function user_engaged($bricabox, $content, $user)
	{
		$query = $this->CI->db->query('select * from engagements
			where content_id = ? and user_id = ? limit 1',
			array($content->id, $user->id));
		if ($query->num_rows())
			return true;
	}
	
	/**
	* callbacks
	*/
	function on_click($bricabox, $content, $user, $type, $value)
	{
		$this->CI->engagement->record_engagement($bricabox, $content, $user, $type, $this, $value);
	}
	
	function on_create_entry($bricabox, $content, $user, $type, $value)
	{
		$this->on_click($bricabox, $content, $user, $type, $value);
	}
}

/**
* Five star
*/
class FivestarEngagement extends EngagementType {
	function form_for_entry($bricabox, $content, $user)
	{
		if (!$this->CI->userland->logged_in())
			return '<a href="/sign_up_or_log_in">sign up or log in to rate this</a>';
			
		$eng = $this->user_engaged($bricabox, $content, $user);
		if ($eng !== false)
			return "<span class=\"rate_stars\" title=\"{$eng->value}.0\"><span>You rated this</span> ".str_repeat('<img src="/assets/images/icons/star.png" alt="*" />', $eng->value).'</span>';
		else
		{
			$form = "";
			for ($i=1; $i<=5; $i++)
			{
				$_label = str_repeat('*', $i);
				$form .= <<<HTML
<form action="/bricabox/{$bricabox->id}/handle_engagement" method="post" style="display: inline;">
	<input type="hidden" name="eng[type]" value="click" />
	<input type="hidden" name="eng[eng_type]" value="fivestar" />
	<input type="hidden" name="eng[content_id]" value="{$content->id}" />
	<input type="hidden" name="eng[user_id]" value="{$user->id}" />
	<input type="hidden" name="eng[redirect]" value="/{$_SERVER['QUERY_STRING']}" />
	<input type="hidden" name="eng[value]" value="{$i}" />
	<span class="rate_stars"><input type="image" id="stars_{$content->id}_{$i}" src="/assets/images/icons/star_dim.png" alt="{$_label}" value="{$_label}" onmouseover="Entry.lightStars({$i}, {$content->id});"/></span>
</form>
HTML;
			}
			return $form;
		}
	}
	
	function count_for_entry($bricabox, $content)
	{
		$cnt = $this->get_count_for($bricabox, $content);
		$cnt = number_format($cnt, 1);
		return "{$cnt} / 5.0";
	}
	
	function small_form_for_entry($bricabox, $content, $user)
	{
		return $this->form_for_entry($bricabox, $content, $user);
	}
	
	function small_count_for_entry($bricabox, $content)
	{
		$cnt = $this->count_for_entry($bricabox, $content);
		return $cnt;
	}
	
	function get_count_for($bricabox, $content)
	{
		// average all the ratings and return the result
		$sum_query = $this->CI->db->query('select sum(engagements.value) as count_sum from engagements
			where content_id = ?', array($content->id));
		
		// total
		$query = $this->CI->db->query('select cached_eng_count from contents
			where id = ?', array($content->id));
		$total_count = $query->first_row()->cached_eng_count;
		
		// result!
		if ($total_count > 0)
			return ($sum_query->first_row()->count_sum) / (float)$total_count;
		else
			return 0.0;
	}
	
	function user_engaged($bricabox, $content, $user)
	{
		$query = $this->CI->db->query('select * from engagements
			where content_id = ? and user_id = ? limit 1',
			array($content->id, $user->id));
		if ($query->num_rows() == 1)
			return $query->first_row();
		else
			return false;
	}
	
	/**
	* callbacks
	*/
	function on_click($bricabox, $content, $user, $type, $value)
	{
		$this->CI->engagement->record_engagement($bricabox, $content, $user, $type, $this, $value);
	}
	
	function on_create_entry($bricabox, $content, $user, $type, $value)
	{
	}
}
?>